import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { App } from 'vue'
import {
  useLoginStore,
  useUserInfoStore,
  useProjectStore,
} from '@/features/store/store'
import { setRequestRouter } from '@/request/request'

const Login = () => import('@/views/Login/login.vue')
const Home = () => import('@/views/Home/home.vue')
const Freind = () => import('@/views/Friend/friend.vue')
const Harvest = () => import('@/views/Harvest/harvest.vue')
const Project = () => import('@/views/Project/project.vue')
const Setting = () => import('@/views/Setting/setting.vue')
const Message = () => import('@/views/Message/message.vue')

const NotFound = () => import('@/components/NotFound.vue')

const noRightRoutes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/home',
  },
  { path: '/login', name: 'Login', component: Login },
]

const rightRoutes: RouteRecordRaw[] = [
  { path: '/home', name: 'Home', component: Home },
  { path: '/friend', name: 'Frined', component: Freind },
  { path: '/harvest', name: 'Harvest', component: Harvest },
  { path: '/project', name: 'Project', component: Project },
  { path: '/setting', name: 'Setting', component: Setting },
  { path: '/subreact', name: 'Message', component: Message },
  { path: '/subreact/:catchAll(.*)*', name: 'MessageSub', component: Message },
]

const notFound: RouteRecordRaw = {
  path: '/:catchAll(.*)*',
  name: '404',
  component: NotFound,
}

let routes: RouteRecordRaw[] = noRightRoutes

const router = createRouter({
  history: createWebHistory(),
  routes,
})

setRequestRouter(router)

router.beforeEach(async (to, from, next) => {
  const { status, setStatusFalse, getStatus } = useLoginStore()
  const { reset, getUserInfo } = useUserInfoStore()

  if (!status && to.path == '/login') return next()
  if (!window.localStorage.getItem('token')) {
    setStatusFalse()
    reset()
    return next('/login')
  }

  if (status) {
    for (const key in rightRoutes) router.addRoute(rightRoutes[key])
    router.addRoute(notFound)

    // 第一次加载，路由还没有注册完成，需要重新定向
    if (from.path === '/login' && to.path === '/homePage') return next('/home')
    next()
  } else {
    if (await getStatus()) {
      useProjectStore().getProjectList()
      getUserInfo()
      for (const key in rightRoutes) router.addRoute(rightRoutes[key])
      router.addRoute(notFound)
      return next(to)
    }

    reset()
    for (const key in rightRoutes) {
      if (router.hasRoute(rightRoutes[key].name))
        router.removeRoute(rightRoutes[key].name)
    }
    next('/login')
  }
})

// 封装路由初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router)
}
